package com.kurt.controller;

import com.kurt.annotation.Log;
import com.kurt.common.Result;
import com.kurt.dto.LoginRequest;
import com.kurt.dto.LoginResponse;
import com.kurt.service.UserService;
import com.kurt.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 处理用户登录、登出等认证相关请求
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController extends BaseController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 用户登录
     *
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @Log(title = "用户登录", businessType = 10)
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            log.info("用户登录请求: {}", loginRequest.getAccount());
            LoginResponse response = userService.login(loginRequest);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage(), e);
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 用户登出
     *
     * @param token 访问令牌
     * @return 登出结果
     */
    @Log(title = "用户登出", businessType = 11)
    @PostMapping("/logout")
    public Result<Boolean> logout(@RequestHeader("Authorization") String token) {
        try {
            // 移除Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            log.info("用户登出请求");
            boolean success = userService.logout(token);
            return Result.success("登出成功", success);
        } catch (Exception e) {
            log.error("用户登出失败: {}", e.getMessage(), e);
            return Result.error("登出失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     *
     * @param token 访问令牌
     * @return 用户信息
     */
    @GetMapping("/userinfo")
    public Result<LoginResponse.UserInfo> getUserInfo(@RequestHeader("Authorization") String token) {
        try {
            // 移除Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            // 从token中获取用户信息
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
            // 这里可以根据需要构建用户信息
            return Result.success("获取用户信息成功", userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
}
